import urllib

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users

import base
import data

from base_page import BaseHandler


class CreateUserHandler(BaseHandler):
  def PreCheckOrRedirect(self):
    # If user not logged in redirect to login page
    if not self.google_user:
      self.RedirectAndRaise(users.create_login_url(self.request.uri))
    # If user already registered, redirect to homepage
    results = data.User().all().filter('google_user =', self.google_user)
    if results.count():
      self.RedirectAndRaise("/")

  def IsNickNameAvailable(self, nickname):
    # Check if nickname is taken in db
    results = data.User().all().filter('nickname =', nickname)
    if results.count():
      return False
    else:
      return True

  def ProcessGet(self):
    self.Setup('create_user.html')
    self.template_values["nickname"] = self.google_user.nickname()
    self.template_values["nick_available"] = \
        self.IsNickNameAvailable(self.google_user.nickname())
    self.template_values["continue_url"] = self.request.get('continue')
    self.Render()

  def ProcessPost(self):
    self.Setup('create_user.html')
    nickname = self.request.get('nickname')
    description = self.request.get('description')
    continue_url = self.request.get('continue')
    self.template_values["continue_url"] = continue_url
    # If nickname is taken in db, ask user to re-enter
    if not self.IsNickNameAvailable(nickname):
      self.template_values["nickname"] = nickname
      self.template_values["nick_available"] = False
      self.template_values["description"] = description
      self.Render()
      return
    # We are cleared to create a new user account 
    new_user = data.User()
    new_user.google_user = self.google_user
    new_user.nickname = nickname
    new_user.description = description
    if users.is_current_user_admin():
      new_user.is_sys_admin = True
    new_user.put()
    # redirect to continue url if available
    if continue_url:
      self.RedirectAndRaise(urllib.unquote(continue_url))
    else:
      self.RedirectAndRaise("/")
